/**
 * @description axios请求封装
 * @author hu-snail 1217437592@qq.com
 */

import axios from 'axios';
import config from './config';
import { Toast } from 'antd-mobile'
let tokenLose = true;

const { baseURL, successCode, invalidCode, requestTimeout, contentType } = config;

const instance = axios.create({
    baseURL,
    timeout: requestTimeout,
    headers: {
        'Content-Type': contentType
    }
});

// request interceptor
instance.interceptors.request.use(
    (configItem) => configItem,
    (error) =>
        // do something with request error
        Promise.reject(error)
);

// response interceptor
instance.interceptors.response.use(
    (response) => {
        const res = response.data;
        if (res.code === invalidCode && tokenLose) {
            tokenLose = false;
        }

        if (successCode.indexOf(res.code) === -1) {
            return Promise.reject(res);
        }
        return res;
    },
    (error) => {
        Toast.show({
            icon: 'fail',
            content: '请求错误'
        })
        return Promise.reject(error)
    }
);

export default instance;
